<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>06-本地存储</title>
  <style>
    .box {
      width: 200px;
      height: 200px;
      border: 1px solid #000;
    }
  </style>
</head>
<body>
  <input type="button" value="红色" id="btnRed">
  <input type="button" value="蓝色" id="btnBlue">
  <input type="button" value="紫色" id="btnPurple">
  <input type="button" value="普通设置按钮" id="btnSet">
  <input type="button" value="普通获取按钮" id="btnGet">
  <div class="box"></div>
  <script>
    // 要求数据持久化，可以使用本地存储
    // 1. 获取页面中的标签对象
    const box = document.querySelector('.box')
    const btnRed = document.getElementById('btnRed')
    const btnBlue = document.getElementById('btnBlue')
    const btnPurple = document.getElementById('btnPurple')
    const btnSet = document.getElementById('btnSet')
    const btnGet = document.getElementById('btnGet')

    box.style.backgroundColor = localStorage.getItem('color')
    // 2. 设置背景颜色
    btnBlue.onclick = function () {
      box.style.backgroundColor = 'blue'
      localStorage.setItem('color','blue')
    }

    btnRed.onclick = function () {
      box.style.backgroundColor = 'red'
      localStorage.setItem('color','red')
    }

    btnPurple.onclick = function () {
      box.style.backgroundColor = 'purple'
      localStorage.setItem('color','purple')
    }

    const obj = {
      name:'jack',
      age:20,
      address:'深圳市'
    }

    const arr = [{id:1,name:'tom',age:20},{id:2,name:'jerry',age:21}]

    btnSet.onclick = function(){
      // localStorage.setItem('stu',JSON.stringify(obj))
      localStorage.setItem('arr',JSON.stringify(arr))
    }
    btnGet.onclick = function(){
      // const stu = localStorage.getItem('stu')
      // console.log(stu,typeof stu)
      // const obj = JSON.parse(stu)
      // console.log(obj,typeof obj)

      const newArr = JSON.parse(localStorage.getItem('arr'))
      console.log(newArr,typeof newArr)
    }

    // localStorage 不主动清除的话，就会一直存在
    // localStorage.setItem(属性名,属性值)
    // localStorage.getItem(属性名)
    // localStorage.removeItem(属性名)
    // localStorage.clear() 清空所有的
    // sessionStorage 关闭页面就会自动清除
  </script>
</body>
</html>